package easy;
/*2025/7/19
17:19*/


import java.util.Arrays;

import java.util.HashMap;
import java.util.Map;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // 创建哈希表存储数组元素值和对应的索引
        Map<Integer, Integer> numMap = new HashMap<>();

        // 遍历数组
        for (int i = 0; i < nums.length; i++) {
            // 计算目标差值
            int complement = target - nums[i];

            // 检查差值是否在哈希表中
            if (numMap.containsKey(complement)) {
                // 找到结果，返回两个索引
                return new int[]{numMap.get(complement), i};
            }

            // 将当前元素存入哈希表
            numMap.put(nums[i], i);
        }

        // 题目保证有解，此处不会执行
        return new int[0];
    }
}
public class Test1 {
    public static void main(String[] args) {
        Solution solution = new Solution();

        // 示例 1
        int[] nums1 = {2, 7, 11, 15};
        int target1 = 9;
        int[] result1 = solution.twoSum(nums1, target1);
        System.out.println(Arrays.toString(result1)); // 输出 [0, 1]

        // 示例 2
        int[] nums2 = {3, 2, 4};
        int target2 = 6;
        int[] result2 = solution.twoSum(nums2, target2);
        System.out.println(Arrays.toString(result2)); // 输出 [1, 2]

        // 示例 3
        int[] nums3 = {3, 3};
        int target3 = 6;
        int[] result3 = solution.twoSum(nums3, target3);
        System.out.println(Arrays.toString(result3)); // 输出 [0, 1]
    }
}